package org.holynite.fieldmanage.managed.controller

import org.holynite.fieldmanage.ejbs.ChargeManagement
import org.holynite.fieldmanage.entities.ChargeRule
import org.holynite.fieldmanage.entities.ChargeScheme
import org.holynite.fieldmanage.managed.model.ChargeRuleFormBean
import org.holynite.fieldmanage.managed.model.ChargeRulesBean
import org.holynite.fieldmanage.managed.model.ChargeSchemeFormBean
import org.holynite.fieldmanage.managed.model.ChargeSchemesBean
import org.holynite.fieldmanage.utils.LocaleString

import javax.annotation.PostConstruct
import javax.ejb.EJB
import javax.faces.bean.ManagedBean
import javax.faces.bean.ManagedProperty
import javax.faces.bean.ViewScoped
import javax.faces.event.ValueChangeEvent
import javax.faces.model.SelectItem
import javax.inject.Inject

/**
 * Created by midnite on 15/1/22.
 */
@ManagedBean
@ViewScoped
class ChargeSchemeBean implements Serializable {


	@EJB(beanName = "chargeControl")
	ChargeManagement chargeService
    @ManagedProperty("#{chargeSchemeFormBean}")
    ChargeSchemeFormBean csForm
    @ManagedProperty("#{chargeSchemesBean}")
    ChargeSchemesBean csBean
    @ManagedProperty("#{chargeRulesBean}")
    ChargeRulesBean crBean
    @ManagedProperty("#{chargeRuleFormBean}")
    ChargeRuleFormBean crForm
	@Inject
	LocaleString locale

	ChargeSchemeBean() {

	}

	def saveScheme() {
		if (csForm.addMode) {
			ChargeScheme newScheme = new ChargeScheme(
				name: csForm.schemeName, enabled: Boolean.parseBoolean(csForm.enableScheme),
				extendRuleTime: Boolean.parseBoolean(csForm.extendTime), preciseCharge: Boolean.parseBoolean(csForm.preciseCharge)
			)
			chargeService.addScheme(newScheme)
		} else {
			def selectedChargeScheme = csBean.findScheme(csForm.selectedScheme)
			selectedChargeScheme.name = csForm.schemeName
			selectedChargeScheme.enabled = Boolean.parseBoolean(csForm.enableScheme)
			selectedChargeScheme.extendRuleTime = Boolean.parseBoolean(csForm.extendTime)
			selectedChargeScheme.preciseCharge = Boolean.parseBoolean(csForm.preciseCharge)
			chargeService.saveScheme(selectedChargeScheme)
            csForm.selectedScheme = ""
		}
		csForm.clearForm()
        crForm.clearForm()
        crForm.clearSearch()
        crBean.clearRules()
        csBean.initiate()
		null
	}

	def removeScheme() {
		chargeService.removeScheme(csForm.selectedScheme)
		csForm.clearForm()
        crForm.clearForm()
        crForm.clearSearch()
        crBean.clearRules()
        csBean.initiate()
		null
	}
}
